如何处理请求
如何处理请求
class IOStream(object):
def __init__(self, socket, ···):
self.socket = socket
self.socket.setblocking(False)
self.io_loop = io_loop or ioloop.IOLoop.instance()
self._state = self.io_loop.ERROR
self.io_loop.add_handler(self.socket.fileno(), self._handle_events, self._state)
def _handle_events(self, fd, events):
if events & self.io_loop.READ:
self._handle_read()
if not self.socket:
return
if events & self.io_loop.WRITE:
if self._connecting:
self._handle_connect()
self._handle_write()
if not self.socket:
return
if events & self.io_loop.ERROR:
self.io_loop.add_callback(self.close)
return
state = self.io_loop.ERROR
if self.reading():
state |= self.io_loop.READ
if self.writing():
state |= self.io_loop.WRITE
if state != self._state:
self._state = state
self.io_loop.update_handler(self.socket.fileno(), self._state)
class HTTPConnection(object):
def __init__(self, stream, address, request_callback, no_keep_alive=False, xheaders=False):
self.stream = stream
self.address = address
self.request_callback = request_callback
···
self._header_callback = stack_context.wrap(self._on_headers)
self.stream.read_until(b("\r\n\r\n"), self._header_callback)
def _on_headers(self, data):
···
eol = data.find("\r\n")
start_line = data[:eol]
method, uri, version = start_line.split(" ")
···
self._request = HTTPRequest(
connection=self, method=method, uri=uri, version=version, headers=headers, remote_ip=self.address[0])
···
self.request_callback(self._request)
class Application(object):
def __call__(self, request):
handlers = self._get_host_handlers(request)
for spec in handlers:
match = spec.regex.match(request.path)
if match:
handler = spec.handler_class(self, request, **spec.kwargs)
handler._execute(transforms, *args, **kwargs)
def _get_host_handlers(self, request):
host = request.host.lower().split(':')[0]
for pattern, handlers in self.handlers:
if pattern.match(host):
return handlers
class RequestHandler(object):
def _execute(self, transforms, *args, **kwargs):
getattr(self, self.request.method.lower())(*args, **kwargs)